"""
管理员主页面
包含订单管理、用户管理、商品管理、统计报表等功能模块
"""

import tkinter as tk
from tkinter import ttk, messagebox
import os
import customtkinter
from ui.pages.scrollable_page import ScrollablePage
from core.services.admin_service import AdminService
from core.models.order import OrderStatus
from core.utils.i18n import t
from core.utils.logger import info, warning, error
from ui.styles.theme import Theme
from datetime import datetime, timedelta


class AdminPage(ScrollablePage):
    """管理员主页面"""
    
    def __init__(self, parent, controller):
        # 先初始化所有需要的属性
        self.admin_service = AdminService()
        self.current_tab = "orders"  # 当前选中的标签页
        self.orders_data = []
        self.users_data = []
        self.products_data = []
        
        # 筛选和搜索状态
        self.order_filters = {
            'status': 'all',
            'user': 'all',
            'date_from': '',
            'date_to': ''
        }
        self.user_filters = {
            'role': 'all',
            'search': ''
        }
        self.product_filters = {
            'category': 'all',
            'stock': 'all',
            'search': ''
        }
        
        # 分页状态
        self.current_page = 1
        self.items_per_page = 20
        
        # 然后调用父类初始化（这会触发 create_widgets()）
        super().__init__(parent, controller)
        
    def create_widgets(self):
        """创建页面组件"""
        content = self.scrollable_frame
        
        # 创建顶部导航栏
        self._create_header(content)
        
        # 创建标签页导航
        self._create_tab_navigation(content)
        
        # 创建主内容区域
        self._create_main_content(content)
        
        # 初始化显示订单管理页面
        self._show_orders_tab()
    
    def update_data(self):
        """更新页面数据（每次显示页面时调用）"""
        # 检查管理员权限
        if not self._check_admin_permission():
            return
        
        # 刷新当前标签页数据
        if hasattr(self, 'current_tab'):
            if self.current_tab == "orders":
                self._load_orders_data()
            elif self.current_tab == "users":
                self._load_users_data()
            elif self.current_tab == "products":
                self._load_products_data()
    
    def _load_users_data(self):
        """加载用户数据"""
        try:
            self.users_data = self.admin_service.get_all_users_with_stats()
            # 应用筛选并更新界面显示
            filtered_users = self._filter_users(self.users_data)
            self._update_users_treeview(filtered_users)
        except Exception as e:
            error(f"Failed to load user data: {e}")
            self.users_data = []
    
    def _load_products_data(self):
        """加载商品数据"""
        try:
            self.products_data = self.admin_service.get_product_sales_stats()
            # 应用筛选并更新界面显示
            filtered_products = self._filter_products(self.products_data)
            self._update_products_treeview(filtered_products)
        except Exception as e:
            error(f"Failed to load product data: {e}")
            self.products_data = []
    
    
    
    def _check_admin_permission(self):
        """检查管理员权限"""
        if not self.controller.auth_service.is_logged_in():
            messagebox.showerror(t("admin.page.access_denied"), t("admin.page.login_required"))
            self.controller.show_page("AdminLoginPage")
            return False
        
        if not self.controller.auth_service.current_user.get_role() == "admin":
            messagebox.showerror(t("admin.page.access_denied"), t("admin.page.admin_only"))
            self.controller.show_page("WelcomePage")
            return False
        
        return True
    
    def _create_header(self, parent):
        """创建顶部导航栏"""
        header_frame = customtkinter.CTkFrame(parent, fg_color=("gray95", "gray20"), corner_radius=10)
        header_frame.pack(fill='x', padx=20, pady=(0, 15))
        
        # 左侧：标题和欢迎信息
        left_frame = customtkinter.CTkFrame(header_frame, fg_color="transparent")
        left_frame.pack(side='left', padx=20, pady=12)
        
        title_label = customtkinter.CTkLabel(
            left_frame,
            text=t("admin.page.title"),
            font=("Arial", 18, "bold"),
            text_color=Theme.get_color('accent')
        )
        title_label.pack(side='left', padx=(0, 20))
        
        # 获取当前用户名，如果未登录则显示默认文本
        current_user = self.controller.auth_service.current_user
        if current_user and hasattr(current_user, 'username'):
            username = current_user.username
        else:
            username = "Admin"
        
        welcome_label = customtkinter.CTkLabel(
            left_frame,
            text=t("admin.page.welcome", username=username),
            font=("Arial", 12),
            text_color=Theme.get_color('fg_secondary')
        )
        welcome_label.pack(side='left')
        
        # 右侧：角色切换器和退出登录按钮
        right_frame = customtkinter.CTkFrame(header_frame, fg_color="transparent")
        right_frame.pack(side='right', padx=20, pady=12)
        
        # 角色切换器
        from ui.components.role_switcher import RoleSwitcher
        self.role_switcher = RoleSwitcher(right_frame, self.controller)
        self.role_switcher.pack(side="left", padx=10)
        
        logout_btn = customtkinter.CTkButton(
            right_frame,
            text=t("admin.page.logout"),
            command=self._logout,
            width=120,
            height=32,
            font=('Arial', 12, 'bold'),
            fg_color=Theme.get_color('error'),
            hover_color="#C0392B",
            corner_radius=8
        )
        logout_btn.pack(side='right')
    
    def _create_tab_navigation(self, parent):
        """创建标签页导航"""
        tab_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        tab_frame.pack(fill='x', padx=20, pady=(0, 15))
        
        # 标签页按钮
        self.tab_buttons = {}
        tabs = [
            ("orders", t("admin.page.tabs.orders")),
            ("users", t("admin.page.tabs.users")),
            ("products", t("admin.page.tabs.products"))
        ]
        
        for tab_id, tab_text in tabs:
            btn = customtkinter.CTkButton(
                tab_frame,
                text=tab_text,
                command=lambda t=tab_id: self._switch_tab(t),
                width=150,
                height=35,
                font=('Arial', 12, 'bold'),
                fg_color=("gray70", "gray30"),
                hover_color=("gray60", "gray40"),
                corner_radius=8
            )
            btn.pack(side='left', padx=5)
            self.tab_buttons[tab_id] = btn
        
        # 设置默认选中状态
        self._update_tab_selection()
    
    def _create_main_content(self, parent):
        """创建主内容区域"""
        self.content_frame = customtkinter.CTkFrame(parent, fg_color="transparent")
        self.content_frame.pack(fill='both', expand=True, padx=20, pady=(0, 20))
    
    def _switch_tab(self, tab_id):
        """切换标签页"""
        self.current_tab = tab_id
        self._update_tab_selection()
        
        # 清除主内容区域
        for widget in self.content_frame.winfo_children():
            widget.destroy()
        
        # 根据标签页显示不同内容
        if tab_id == "orders":
            self._show_orders_tab()
        elif tab_id == "users":
            self._show_users_tab()
        elif tab_id == "products":
            self._show_products_tab()
    
    def _update_tab_selection(self):
        """更新标签页选中状态"""
        for tab_id, btn in self.tab_buttons.items():
            if tab_id == self.current_tab:
                btn.configure(
                    fg_color=Theme.get_color('accent'),
                    hover_color=Theme.get_color('accent_hover')
                )
            else:
                btn.configure(
                    fg_color=("gray70", "gray30"),
                    hover_color=("gray60", "gray40")
                )
    
    def _show_orders_tab(self):
        """显示订单管理标签页"""
        # 创建订单管理界面
        orders_frame = customtkinter.CTkFrame(self.content_frame, fg_color=("gray95", "gray20"), corner_radius=10)
        orders_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 标题容器
        title_container = customtkinter.CTkFrame(orders_frame, fg_color="transparent")
        title_container.pack(fill='x', padx=20, pady=20)
        
        # 标题
        title_label = customtkinter.CTkLabel(
            title_container,
            text=t("admin.page.orders.title"),
            font=("Arial", 18, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(side='left')
        
        # 搜索和筛选区域
        self._create_orders_filters(orders_frame)
        
        # 订单列表区域
        self._create_orders_list(orders_frame)
        
        # 加载订单数据
        self._load_orders_data()
    
    def _create_orders_filters(self, parent):
        """创建订单筛选区域"""
        filter_frame = ttk.LabelFrame(parent, text="Filter & Search", padding=10)
        filter_frame.pack(fill='x', pady=(0, 10))
        
        # 第一行：搜索框
        search_frame = ttk.Frame(filter_frame)
        search_frame.pack(fill='x', pady=(0, 10))
        
        ttk.Label(search_frame, text="Search:").pack(side='left', padx=(0, 5))
        self.orders_search_var = tk.StringVar()
        self.orders_search_entry = ttk.Entry(
            search_frame,
            textvariable=self.orders_search_var,
            width=40
        )
        self.orders_search_entry.pack(side='left', padx=(0, 10))
        self.orders_search_entry.bind('<KeyRelease>', self._on_orders_search)
        
        search_btn = ttk.Button(
            search_frame,
            text="Search",
            command=self._search_orders
        )
        search_btn.pack(side='left', padx=(0, 20))
        
        # 第二行：筛选选项
        filter_row = ttk.Frame(filter_frame)
        filter_row.pack(fill='x')
        
        # 状态筛选
        ttk.Label(filter_row, text="Status:").pack(side='left', padx=(0, 5))
        self.status_var = tk.StringVar(value='all')
        status_combo = ttk.Combobox(
            filter_row,
            textvariable=self.status_var,
            values=['all', 'pending', 'paid', 'shipped', 'completed', 'cancelled'],
            state='readonly',
            width=15
        )
        status_combo.pack(side='left', padx=(0, 20))
        status_combo.bind('<<ComboboxSelected>>', self._on_orders_filter_change)
        
        # 用户筛选
        ttk.Label(filter_row, text="User:").pack(side='left', padx=(0, 5))
        self.user_var = tk.StringVar(value='all')
        user_combo = ttk.Combobox(
            filter_row,
            textvariable=self.user_var,
            values=['all'],  # 将在加载数据时更新
            state='readonly',
            width=15
        )
        user_combo.pack(side='left', padx=(0, 20))
        user_combo.bind('<<ComboboxSelected>>', self._on_orders_filter_change)
        
        # 刷新按钮
        refresh_btn = ttk.Button(
            filter_row,
            text="Refresh",
            command=self._load_orders_data
        )
        refresh_btn.pack(side='right')
    
    def _create_orders_list(self, parent):
        """创建订单列表区域"""
        # 创建滚动框架
        list_frame = ttk.Frame(parent)
        list_frame.pack(fill='both', expand=True)
        
        # 创建Treeview
        columns = ('order_id', 'user', 'total', 'status', 'created_at', 'actions')
        self.orders_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=15, style='Admin.Treeview')
        
        # 设置列标题
        self.orders_tree.heading('order_id', text='Order ID')
        self.orders_tree.heading('user', text='User')
        self.orders_tree.heading('total', text='Total')
        self.orders_tree.heading('status', text='Status')
        self.orders_tree.heading('created_at', text='Created At')
        self.orders_tree.heading('actions', text='Actions')
        
        # 设置列宽
        self.orders_tree.column('order_id', width=120)
        self.orders_tree.column('user', width=100)
        self.orders_tree.column('total', width=80)
        self.orders_tree.column('status', width=80)
        self.orders_tree.column('created_at', width=120)
        self.orders_tree.column('actions', width=100)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient='vertical', command=self.orders_tree.yview)
        self.orders_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.orders_tree.pack(side='left', fill='both', expand=True)
        scrollbar.pack(side='right', fill='y')
        
        # 绑定双击事件
        self.orders_tree.bind('<Double-1>', self._on_order_double_click)
    
    def _load_orders_data(self):
        """加载订单数据"""
        try:
            # 获取所有订单及用户信息
            self.orders_data = self.admin_service.get_all_orders_with_user_info()
            
            # 应用筛选
            filtered_orders = self._filter_orders(self.orders_data)
            
            # 更新Treeview
            self._update_orders_treeview(filtered_orders)
            
            # 更新用户筛选选项
            self._update_user_filter_options()
            
        except Exception as e:
            error(f"Failed to load order data: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.load_failed", error=str(e)))
    
    def _filter_orders(self, orders):
        """筛选订单"""
        filtered = orders
        
        # 状态筛选
        if self.order_filters['status'] != 'all':
            filtered = [o for o in filtered if o.get('status') == self.order_filters['status']]
        
        # 用户筛选
        if self.order_filters['user'] != 'all':
            filtered = [o for o in filtered if o.get('user_info', {}).get('username') == self.order_filters['user']]
        
        # 搜索筛选
        search_text = self.orders_search_var.get().lower()
        if search_text:
            filtered = [o for o in filtered if 
                       search_text in o.get('order_id', '').lower() or
                       search_text in o.get('user_info', {}).get('username', '').lower()]
        
        return filtered
    
    def _update_orders_treeview(self, orders):
        """更新订单Treeview"""
        # 清空现有数据
        for item in self.orders_tree.get_children():
            self.orders_tree.delete(item)
        
        # 添加订单数据
        for order in orders:
            user_info = order.get('user_info', {})
            status_display = self._get_status_display(order.get('status', ''))
            
            self.orders_tree.insert('', 'end', values=(
                order.get('order_id', ''),
                user_info.get('username', 'Unknown User'),
                f"¥{order.get('total', 0):.2f}",
                status_display,
                order.get('created_at', '')[:19] if order.get('created_at') else '',
                'View Details'
            ))
    
    def _get_status_display(self, status):
        """获取状态显示文本"""
        status_map = {
            'pending': 'Pending',
            'paid': 'Paid',
            'shipped': 'Shipped',
            'completed': 'Completed',
            'cancelled': 'Cancelled'
        }
        return status_map.get(status, status)
    
    def _update_user_filter_options(self):
        """更新用户筛选选项"""
        users = set()
        for order in self.orders_data:
            user_info = order.get('user_info', {})
            if user_info.get('username'):
                users.add(user_info['username'])
        
        user_combo = None
        for widget in self.content_frame.winfo_children():
            if isinstance(widget, ttk.LabelFrame):
                for child in widget.winfo_children():
                    if isinstance(child, ttk.Frame):
                        for grandchild in child.winfo_children():
                            if isinstance(grandchild, ttk.Combobox) and grandchild.cget('values') == ['all']:
                                user_combo = grandchild
                                break
        
        if user_combo:
            user_combo['values'] = ['all'] + sorted(list(users))
    
    def _on_orders_search(self, event):
        """订单搜索事件处理"""
        # 应用搜索筛选并刷新显示
        filtered_orders = self._filter_orders(self.orders_data)
        self._update_orders_treeview(filtered_orders)
    
    def _search_orders(self):
        """搜索订单"""
        # 应用搜索筛选并刷新显示
        filtered_orders = self._filter_orders(self.orders_data)
        self._update_orders_treeview(filtered_orders)
    
    def _on_orders_filter_change(self, event):
        """订单筛选变化事件处理"""
        # 更新筛选条件
        self.order_filters['status'] = self.status_var.get()
        self.order_filters['user'] = self.user_var.get()
        
        # 应用筛选并刷新显示
        filtered_orders = self._filter_orders(self.orders_data)
        self._update_orders_treeview(filtered_orders)
    
    def _on_order_double_click(self, event):
        """订单双击事件处理"""
        selection = self.orders_tree.selection()
        if selection:
            item = self.orders_tree.item(selection[0])
            order_id = item['values'][0]
            self._show_order_details(order_id)
    
    def _show_order_details(self, order_id):
        """显示订单详情"""
        try:
            # 验证订单ID
            if not order_id:
                messagebox.showerror(t("common.error"), t("admin.page.invalid_order_id"))
                return
            
            # 查找订单
            order = None
            for o in self.orders_data:
                if o.get('order_id') == order_id:
                    order = o
                    break
            
            if not order:
                messagebox.showerror(t("common.error"), t("admin.page.order_not_found", order_id=order_id))
                return
            
            # 创建详情对话框
            self._create_order_details_dialog(order)
        except Exception as e:
            error(f"显示订单详情失败: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.show_details_error", error=str(e)))
    
    def _create_order_details_dialog(self, order):
        """创建订单详情对话框"""
        try:
            dialog = customtkinter.CTkToplevel(self)
            dialog.title(f"Order Details - {order.get('order_id', '')}")
            dialog.geometry("750x650")
            dialog.resizable(True, True)
            dialog.minsize(700, 550)
            
            # 设置对话框居中
            dialog.transient(self)
            dialog.grab_set()
            dialog.update_idletasks()
            x = (dialog.winfo_screenwidth() // 2) - (750 // 2)
            y = (dialog.winfo_screenheight() // 2) - (650 // 2)
            dialog.geometry(f"+{x}+{y}")
        
            # 主容器
            main_frame = customtkinter.CTkFrame(dialog, fg_color="transparent")
            main_frame.pack(fill='both', expand=True, padx=20, pady=20)
            
            # 标题
            title_label = customtkinter.CTkLabel(
                main_frame,
                text=f"📋 Order Details - {order.get('order_id', '')}",
                font=('Arial', 18, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            title_label.pack(pady=(0, 15))
            
            # 分隔线
            customtkinter.CTkFrame(main_frame, height=2, fg_color=Theme.get_color('border')).pack(fill='x', pady=(0, 20))
            
            # 创建滚动框架
            scrollable_frame = customtkinter.CTkScrollableFrame(main_frame, fg_color="transparent")
            scrollable_frame.pack(fill='both', expand=True)
            
            # 订单基本信息
            info_frame = customtkinter.CTkFrame(scrollable_frame, fg_color=("gray95", "gray20"))
            info_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
            
            info_title = customtkinter.CTkLabel(
                info_frame,
                text="📌 Order Information",
                font=('Arial', 14, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            info_title.pack(anchor='w', pady=(0, 12))
            
            # 订单详细信息（使用更美观的格式）
            details = [
                ("Order ID:", order.get('order_id', '')),
                ("User:", order.get('user_info', {}).get('username', 'Unknown User')),
                ("Email:", order.get('user_info', {}).get('email', '')),
                ("Status:", self._get_status_display(order.get('status', ''))),
                ("Total:", f"¥{order.get('total', 0):.2f}"),
                ("Created At:", order.get('created_at', '')),
                ("Updated At:", order.get('updated_at', '')),
                ("Shipping Address:", order.get('shipping_address', 'Not Provided'))
            ]
            
            for label, value in details:
                detail_frame = customtkinter.CTkFrame(info_frame, fg_color="transparent")
                detail_frame.pack(fill='x', pady=4)
                customtkinter.CTkLabel(
                    detail_frame,
                    text=label,
                    font=('Arial', 11, 'bold'),
                    text_color=Theme.get_color('fg_secondary'),
                    width=140,
                    anchor='w'
                ).pack(side='left')
                customtkinter.CTkLabel(
                    detail_frame,
                    text=str(value),
                    font=('Arial', 11),
                    text_color=Theme.get_color('fg_primary'),
                    anchor='w'
                ).pack(side='left', fill='x', expand=True)
            
            # 商品列表
            items_frame = customtkinter.CTkFrame(scrollable_frame, fg_color=("gray95", "gray20"))
            items_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
            
            items_title = customtkinter.CTkLabel(
                items_frame,
                text="🛍️ Product List",
                font=('Arial', 14, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            items_title.pack(anchor='w', pady=(0, 12))
            
            items = order.get('items', [])
            if items:
                for item in items:
                    item_frame = customtkinter.CTkFrame(items_frame, fg_color="transparent")
                    item_frame.pack(fill='x', pady=6)
                    item_text = f"{item.get('name', '')} × {item.get('quantity', 1)}"
                    customtkinter.CTkLabel(
                        item_frame,
                        text=item_text,
                        font=('Arial', 11),
                        text_color=Theme.get_color('fg_primary'),
                        anchor='w'
                    ).pack(side='left', fill='x', expand=True)
                    customtkinter.CTkLabel(
                        item_frame,
                        text=f"¥{item.get('subtotal', 0):.2f}",
                        font=('Arial', 11, 'bold'),
                        text_color=Theme.get_color('accent')
                    ).pack(side='right', padx=(10, 0))
            else:
                customtkinter.CTkLabel(
                    items_frame,
                    text="No product information",
                    font=('Arial', 11),
                    text_color=Theme.get_color('fg_tertiary')
                ).pack(anchor='w', pady=10)
            
            # 操作按钮
            button_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
            button_frame.pack(fill='x', pady=(15, 0))
            
            # 根据订单状态显示不同的操作按钮
            status = order.get('status', '')
            order_id = order.get('order_id', '')
            
            if status == 'paid':
                customtkinter.CTkButton(
                    button_frame,
                    text="Mark as Shipped",
                    command=lambda: self._update_order_status_and_close(order_id, 'shipped', dialog),
                    width=140,
                    height=35,
                    fg_color=Theme.get_color('accent'),
                    hover_color=Theme.get_color('accent_hover'),
                    corner_radius=8
                ).pack(side='left', padx=(0, 8))
            elif status == 'shipped':
                customtkinter.CTkButton(
                    button_frame,
                    text="Mark as Completed",
                    command=lambda: self._update_order_status_and_close(order_id, 'completed', dialog),
                    width=140,
                    height=35,
                    fg_color=Theme.get_color('success'),
                    hover_color='#229954',
                    corner_radius=8
                ).pack(side='left', padx=(0, 8))
            
            customtkinter.CTkButton(
                button_frame,
                text="Close",
                command=dialog.destroy,
                width=120,
                height=35,
                fg_color=Theme.get_color('fg_secondary'),
                hover_color=Theme.get_color('fg_tertiary'),
                corner_radius=8
            ).pack(side='right')
            
        except Exception as e:
            error(f"Failed to create order details dialog: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.create_dialog_error", error=str(e)))
    
    def _update_order_status(self, order_id, new_status):
        """更新订单状态"""
        try:
            from core.models.order import OrderStatus
            status_enum = OrderStatus(new_status)
            
            if self.admin_service.order_service.update_order_status(order_id, status_enum):
                messagebox.showinfo(t("common.success"), t("admin.page.status_updated", status=self._get_status_display(new_status)))
                self._load_orders_data()  # 刷新订单列表
            else:
                messagebox.showerror(t("common.error"), t("admin.page.update_status_failed"))
        except Exception as e:
            error(f"更新订单状态失败: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.update_status_error", error=str(e)))
    
    def _update_order_status_and_close(self, order_id, new_status, dialog):
        """更新订单状态并关闭对话框"""
        try:
            from core.models.order import OrderStatus
            
            # 验证订单ID
            if not order_id:
                messagebox.showerror(t("common.error"), t("admin.page.invalid_order_id"))
                return
            
            # 验证状态
            try:
                status_enum = OrderStatus(new_status)
            except ValueError:
                messagebox.showerror(t("common.error"), t("admin.page.invalid_status", status=new_status))
                return
            
            # 更新订单状态
            if self.admin_service.order_service.update_order_status(order_id, status_enum):
                messagebox.showinfo(t("common.success"), t("admin.page.status_updated_success", order_id=order_id, status=self._get_status_display(new_status)))
                dialog.destroy()  # 关闭对话框
                self._load_orders_data()  # 刷新订单列表
            else:
                messagebox.showerror(t("common.error"), t("admin.page.update_retry_error", order_id=order_id))
        except Exception as e:
            error(f"更新订单状态失败: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.update_error", error=str(e)))
    
    def _show_users_tab(self):
        """显示用户管理标签页"""
        # 创建用户管理界面
        users_frame = customtkinter.CTkFrame(self.content_frame, fg_color=("gray95", "gray20"), corner_radius=10)
        users_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 标题容器
        title_container = customtkinter.CTkFrame(users_frame, fg_color="transparent")
        title_container.pack(fill='x', padx=20, pady=20)
        
        # 标题
        title_label = customtkinter.CTkLabel(
            title_container,
            text=t("admin.page.users.title"),
            font=("Arial", 18, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(side='left')
        
        # 搜索和筛选区域
        self._create_users_filters(users_frame)
        
        # 用户列表区域
        self._create_users_list(users_frame)
        
        # 加载用户数据
        self._load_users_data()
    
    def _create_users_filters(self, parent):
        """创建用户筛选区域"""
        filter_frame = ttk.LabelFrame(parent, text="Search & Filter", padding=10)
        filter_frame.pack(fill='x', pady=(0, 10))
        
        # 搜索框
        search_frame = ttk.Frame(filter_frame)
        search_frame.pack(fill='x', pady=(0, 10))
        
        ttk.Label(search_frame, text="Search:").pack(side='left', padx=(0, 5))
        self.users_search_var = tk.StringVar()
        self.users_search_entry = ttk.Entry(
            search_frame,
            textvariable=self.users_search_var,
            width=40
        )
        self.users_search_entry.pack(side='left', padx=(0, 10))
        self.users_search_entry.bind('<KeyRelease>', self._on_users_search)
        
        search_btn = ttk.Button(
            search_frame,
            text="Search",
            command=self._search_users
        )
        search_btn.pack(side='left', padx=(0, 20))
        
        # 角色筛选
        filter_row = ttk.Frame(filter_frame)
        filter_row.pack(fill='x')
        
        ttk.Label(filter_row, text="Role:").pack(side='left', padx=(0, 5))
        self.users_role_var = tk.StringVar(value='all')
        role_combo = ttk.Combobox(
            filter_row,
            textvariable=self.users_role_var,
            values=['all', 'customer', 'seller', 'admin'],
            state='readonly',
            width=15
        )
        role_combo.pack(side='left', padx=(0, 20))
        role_combo.bind('<<ComboboxSelected>>', self._on_users_filter_change)
        
        # 刷新按钮
        refresh_btn = ttk.Button(
            filter_row,
            text="Refresh",
            command=self._load_users_data
        )
        refresh_btn.pack(side='right')
    
    def _create_users_list(self, parent):
        """创建用户列表区域"""
        # 创建滚动框架
        list_frame = ttk.Frame(parent)
        list_frame.pack(fill='both', expand=True)
        
        # 创建Treeview
        columns = ('user_id', 'username', 'email', 'role', 'created_at', 'last_login', 'actions')
        self.users_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=15, style='Admin.Treeview')
        
        # 设置列标题
        self.users_tree.heading('user_id', text='User ID')
        self.users_tree.heading('username', text='Username')
        self.users_tree.heading('email', text='Email')
        self.users_tree.heading('role', text='Role')
        self.users_tree.heading('created_at', text='Registration Date')
        self.users_tree.heading('last_login', text='Last Login')
        self.users_tree.heading('actions', text='Actions')
        
        # 设置列宽
        self.users_tree.column('user_id', width=80)
        self.users_tree.column('username', width=120)
        self.users_tree.column('email', width=200)
        self.users_tree.column('role', width=80)
        self.users_tree.column('created_at', width=120)
        self.users_tree.column('last_login', width=120)
        self.users_tree.column('actions', width=100)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient='vertical', command=self.users_tree.yview)
        self.users_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.users_tree.pack(side='left', fill='both', expand=True)
        scrollbar.pack(side='right', fill='y')
        
        # 绑定双击事件
        self.users_tree.bind('<Double-1>', self._on_user_double_click)
    
    def _on_users_search(self, event):
        """用户搜索事件处理"""
        # 应用搜索筛选并刷新显示
        filtered_users = self._filter_users(self.users_data)
        self._update_users_treeview(filtered_users)
    
    def _search_users(self):
        """搜索用户"""
        # 应用搜索筛选并刷新显示
        filtered_users = self._filter_users(self.users_data)
        self._update_users_treeview(filtered_users)
    
    def _on_users_filter_change(self, event):
        """用户筛选变化事件处理"""
        # 更新筛选条件
        self.user_filters['role'] = self.users_role_var.get()
        
        # 应用筛选并刷新显示
        filtered_users = self._filter_users(self.users_data)
        self._update_users_treeview(filtered_users)
    
    def _filter_users(self, users):
        """筛选用户"""
        filtered = users
        
        # 角色筛选
        if self.user_filters['role'] != 'all':
            filtered = [u for u in filtered if u.get('role') == self.user_filters['role']]
        
        # 搜索筛选
        search_text = self.users_search_var.get().lower()
        if search_text:
            filtered = [u for u in filtered if 
                       search_text in u.get('username', '').lower() or
                       search_text in u.get('email', '').lower() or
                       search_text in str(u.get('user_id', '')).lower()]
        
        return filtered
    
    def _update_users_treeview(self, users):
        """更新用户Treeview"""
        # 清空现有数据
        for item in self.users_tree.get_children():
            self.users_tree.delete(item)
        
        # 添加用户数据
        for user in users:
            role_display = self._get_role_display(user.get('role', ''))
            
            self.users_tree.insert('', 'end', values=(
                user.get('user_id', ''),
                user.get('username', ''),
                user.get('email', ''),
                role_display,
                user.get('created_at', '')[:19] if user.get('created_at') else '',
                user.get('last_login', '')[:19] if user.get('last_login') else 'Never Logged In',
                'View Details'
            ))
    
    def _get_role_display(self, role):
        """获取角色显示文本"""
        role_map = {
            'customer': 'Customer',
            'seller': 'Seller',
            'admin': 'Admin'
        }
        return role_map.get(role, role)
    
    def _on_user_double_click(self, event):
        """用户双击事件处理"""
        selection = self.users_tree.selection()
        if selection:
            item = self.users_tree.item(selection[0])
            user_id = item['values'][0]
            self._show_user_details(user_id)
    
    def _show_user_details(self, user_id):
        """显示用户详情"""
        try:
            # 查找用户
            user = None
            for u in self.users_data:
                if str(u.get('user_id')) == str(user_id):
                    user = u
                    break
            
            if not user:
                messagebox.showerror(t("common.error"), t("admin.page.user_not_found", user_id=user_id))
                return
            
            # 创建详情对话框
            self._create_user_details_dialog(user)
        except Exception as e:
            error(f"显示用户详情失败: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.user_show_details_error", error=str(e)))
    
    def _create_user_details_dialog(self, user):
        """创建用户详情对话框"""
        try:
            dialog = customtkinter.CTkToplevel(self)
            dialog.title(f"User Details - {user.get('username', '')}")
            dialog.geometry("650x580")
            dialog.resizable(True, True)
            dialog.minsize(600, 500)
            
            # 设置对话框居中
            dialog.transient(self)
            dialog.grab_set()
            dialog.update_idletasks()
            x = (dialog.winfo_screenwidth() // 2) - (650 // 2)
            y = (dialog.winfo_screenheight() // 2) - (580 // 2)
            dialog.geometry(f"+{x}+{y}")
            
            # 主容器
            main_frame = customtkinter.CTkFrame(dialog, fg_color="transparent")
            main_frame.pack(fill='both', expand=True, padx=20, pady=20)
            
            # 标题
            title_label = customtkinter.CTkLabel(
                main_frame,
                text=f"👤 User Details - {user.get('username', '')}",
                font=('Arial', 18, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            title_label.pack(pady=(0, 15))
            
            # 分隔线
            customtkinter.CTkFrame(main_frame, height=2, fg_color=Theme.get_color('border')).pack(fill='x', pady=(0, 20))
            
            # 用户基本信息
            info_frame = customtkinter.CTkFrame(main_frame, fg_color=("gray95", "gray20"))
            info_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
            
            info_title = customtkinter.CTkLabel(
                info_frame,
                text="📌 User Information",
                font=('Arial', 14, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            info_title.pack(anchor='w', pady=(0, 12))
            
            # 用户详细信息（使用更美观的格式）
            details = [
                ("User ID:", user.get('user_id', '')),
                ("Username:", user.get('username', '')),
                ("Email:", user.get('email', '')),
                ("Role:", self._get_role_display(user.get('role', ''))),
                ("Registration Date:", user.get('created_at', '')),
                ("Last Login:", user.get('last_login', 'Never Logged In'))
            ]
            
            for label, value in details:
                detail_frame = customtkinter.CTkFrame(info_frame, fg_color="transparent")
                detail_frame.pack(fill='x', pady=4)
                customtkinter.CTkLabel(
                    detail_frame,
                    text=label,
                    font=('Arial', 11, 'bold'),
                    text_color=Theme.get_color('fg_secondary'),
                    width=150,
                    anchor='w'
                ).pack(side='left')
                customtkinter.CTkLabel(
                    detail_frame,
                    text=str(value),
                    font=('Arial', 11),
                    text_color=Theme.get_color('fg_primary'),
                    anchor='w'
                ).pack(side='left', fill='x', expand=True)
            
            # 操作按钮
            button_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
            button_frame.pack(fill='x', pady=(15, 0))
            
            # 编辑用户按钮
            customtkinter.CTkButton(
                button_frame,
                text="Edit User Info",
                command=lambda: self._edit_user_dialog(user, dialog),
                width=130,
                height=35,
                fg_color=Theme.get_color('accent'),
                hover_color=Theme.get_color('accent_hover'),
                corner_radius=8
            ).pack(side='left', padx=(0, 8))
            
            # 重置密码按钮
            customtkinter.CTkButton(
                button_frame,
                text="Reset Password",
                command=lambda: self._reset_password_dialog(user),
                width=130,
                height=35,
                fg_color=Theme.get_color('warning'),
                hover_color='#D68910',
                corner_radius=8
            ).pack(side='left', padx=(0, 8))
            
            customtkinter.CTkButton(
                button_frame,
                text="Close",
                command=dialog.destroy,
                width=120,
                height=35,
                fg_color=Theme.get_color('fg_secondary'),
                hover_color=Theme.get_color('fg_tertiary'),
                corner_radius=8
            ).pack(side='right')
            
        except Exception as e:
            error(f"Failed to create user details dialog: {e}")
            messagebox.showerror(t("common.error"), t("admin.page.user_create_dialog_error", error=str(e)))
    
    def _edit_user_dialog(self, user, parent_dialog=None):
        """创建用户编辑对话框"""
        try:
            edit_dialog = tk.Toplevel(self)
            edit_dialog.title(f"Edit User - {user.get('username', '')}")
            edit_dialog.geometry("500x400")
            edit_dialog.resizable(True, True)
            
            # 设置对话框居中
            edit_dialog.transient(self)
            edit_dialog.grab_set()
            
            # 表单框架
            form_frame = ttk.LabelFrame(edit_dialog, text="Edit User Information", padding=15)
            form_frame.pack(fill='both', expand=True, padx=10, pady=10)
            
            # 用户名
            ttk.Label(form_frame, text="Username:").grid(row=0, column=0, sticky='e', padx=5, pady=5)
            username_var = tk.StringVar(value=user.get('username', ''))
            username_entry = ttk.Entry(form_frame, textvariable=username_var, width=25)
            username_entry.grid(row=0, column=1, padx=5, pady=5)
            
            # 邮箱
            ttk.Label(form_frame, text="Email:").grid(row=1, column=0, sticky='e', padx=5, pady=5)
            email_var = tk.StringVar(value=user.get('email', ''))
            email_entry = ttk.Entry(form_frame, textvariable=email_var, width=25)
            email_entry.grid(row=1, column=1, padx=5, pady=5)
            
            # 角色
            ttk.Label(form_frame, text="Role:").grid(row=2, column=0, sticky='e', padx=5, pady=5)
            role_var = tk.StringVar(value=user.get('role', 'customer'))
            role_combo = ttk.Combobox(
                form_frame, 
                textvariable=role_var, 
                values=['customer', 'seller', 'admin'], 
                state='readonly',
                width=22
            )
            role_combo.grid(row=2, column=1, padx=5, pady=5)
            
            # 按钮框架
            button_frame = ttk.Frame(edit_dialog)
            button_frame.pack(fill='x', padx=10, pady=10)
            
            def save_changes():
                try:
                    # 收集表单数据
                    new_username = username_var.get().strip()
                    new_email = email_var.get().strip()
                    new_role = role_var.get()
                    
                    # 验证输入
                    if not new_username or not new_email:
                        messagebox.showwarning(t("admin.page.input_error"), t("admin.page.username_email_required"))
                        return
                    
                    if len(new_username) < 3:
                        messagebox.showwarning("Input Error", "Username must be at least 3 characters")
                        return
                    
                    # 验证邮箱格式
                    if '@' not in new_email or '.' not in new_email.split('@')[1]:
                        messagebox.showwarning("Input Error", "Please enter a valid email address")
                        return
                    
                    # 确认更改
                    if messagebox.askyesno("Confirm Changes", f"Are you sure you want to update user information?\n\nUsername: {new_username}\nEmail: {new_email}\nRole: {self._get_role_display(new_role)}"):
                        # 调用服务更新用户信息
                        success = self.admin_service.update_user_info(
                            user.get('user_id'), 
                            username=new_username,
                            email=new_email,
                            role=new_role
                        )
                        
                        if success:
                            messagebox.showinfo("Success", "User information updated successfully")
                            edit_dialog.destroy()
                            if parent_dialog:
                                parent_dialog.destroy()
                            # 刷新用户列表
                            self._load_users_data()
                        else:
                            messagebox.showerror("Error", "Failed to update user information, please check input data")
                
                except Exception as e:
                    error(f"Failed to save user information: {e}")
                    messagebox.showerror("Error", f"An error occurred while saving user information: {str(e)}")
            
            ttk.Button(button_frame, text="Save", command=save_changes).pack(side='left', padx=5)
            ttk.Button(button_frame, text="Cancel", command=edit_dialog.destroy).pack(side='right', padx=5)
            
        except Exception as e:
            error(f"创建用户编辑对话框失败: {e}")
            messagebox.showerror("错误", f"创建用户编辑对话框时发生错误: {str(e)}")
    
    def _reset_password_dialog(self, user):
        """创建重置密码对话框"""
        try:
            password_dialog = tk.Toplevel(self)
            password_dialog.title(f"Reset Password - {user.get('username', '')}")
            password_dialog.geometry("450x250")
            password_dialog.resizable(True, True)
            
            # 设置对话框居中
            password_dialog.transient(self)
            password_dialog.grab_set()
            
            # 表单框架
            form_frame = ttk.LabelFrame(password_dialog, text="Reset User Password", padding=15)
            form_frame.pack(fill='both', expand=True, padx=10, pady=10)
            
            # 新密码
            ttk.Label(form_frame, text="New Password:").grid(row=0, column=0, sticky='e', padx=5, pady=5)
            password_var = tk.StringVar()
            password_entry = ttk.Entry(form_frame, textvariable=password_var, show="*", width=25)
            password_entry.grid(row=0, column=1, padx=5, pady=5)
            
            # 确认密码
            ttk.Label(form_frame, text="Confirm Password:").grid(row=1, column=0, sticky='e', padx=5, pady=5)
            confirm_password_var = tk.StringVar()
            confirm_password_entry = ttk.Entry(form_frame, textvariable=confirm_password_var, show="*", width=25)
            confirm_password_entry.grid(row=1, column=1, padx=5, pady=5)
            
            # 提示信息
            ttk.Label(form_frame, text="Password requirements: at least 8 characters, including letters, numbers and special characters", 
                     font=("Arial", 8), foreground="#666").grid(row=2, column=0, columnspan=2, pady=5)
            
            # 按钮框架
            button_frame = ttk.Frame(password_dialog)
            button_frame.pack(fill='x', padx=10, pady=10)
            
            def reset_password():
                try:
                    new_password = password_var.get()
                    confirm_password = confirm_password_var.get()
                    
                    # 验证输入
                    if not new_password or not confirm_password:
                        messagebox.showwarning("输入错误", "请填写密码和确认密码")
                        return
                    
                    if new_password != confirm_password:
                        messagebox.showwarning("输入错误", "两次输入的密码不一致")
                        return
                    
                    # 确认重置
                    if messagebox.askyesno("确认重置", f"确定要重置用户 {user.get('username', '')} 的密码吗？"):
                        # 调用服务重置密码
                        success = self.admin_service.reset_user_password(
                            user.get('user_id'), 
                            new_password
                        )
                        
                        if success:
                            messagebox.showinfo("成功", "密码重置成功")
                            password_dialog.destroy()
                        else:
                            messagebox.showerror("错误", "密码重置失败，请检查密码是否符合要求")
                
                except Exception as e:
                    error(f"重置密码失败: {e}")
                    messagebox.showerror("错误", f"重置密码时发生错误: {str(e)}")
            
            ttk.Button(button_frame, text="Reset", command=reset_password).pack(side='left', padx=5)
            ttk.Button(button_frame, text="Cancel", command=password_dialog.destroy).pack(side='right', padx=5)
            
        except Exception as e:
            error(f"创建重置密码对话框失败: {e}")
            messagebox.showerror("错误", f"创建重置密码对话框时发生错误: {str(e)}")
    
    def _show_products_tab(self):
        """显示商品管理标签页"""
        # 创建商品管理界面
        products_frame = customtkinter.CTkFrame(self.content_frame, fg_color=("gray95", "gray20"), corner_radius=10)
        products_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 标题容器
        title_container = customtkinter.CTkFrame(products_frame, fg_color="transparent")
        title_container.pack(fill='x', padx=20, pady=20)
        
        # 标题
        title_label = customtkinter.CTkLabel(
            title_container,
            text=t("admin.page.products.title"),
            font=("Arial", 18, "bold"),
            text_color=Theme.get_color('fg_primary')
        )
        title_label.pack(side='left')
        
        # 搜索和筛选区域
        self._create_products_filters(products_frame)
        
        # 商品列表区域
        self._create_products_list(products_frame)
        
        # 加载商品数据
        self._load_products_data()
    
    def _create_products_filters(self, parent):
        """创建商品筛选区域"""
        filter_frame = ttk.LabelFrame(parent, text="Search & Filter", padding=10)
        filter_frame.pack(fill='x', pady=(0, 10))
        
        # 搜索框
        search_frame = ttk.Frame(filter_frame)
        search_frame.pack(fill='x', pady=(0, 10))
        
        ttk.Label(search_frame, text="Search:").pack(side='left', padx=(0, 5))
        self.products_search_var = tk.StringVar()
        self.products_search_entry = ttk.Entry(
            search_frame,
            textvariable=self.products_search_var,
            width=40
        )
        self.products_search_entry.pack(side='left', padx=(0, 10))
        self.products_search_entry.bind('<KeyRelease>', self._on_products_search)
        
        search_btn = ttk.Button(
            search_frame,
            text="Search",
            command=self._search_products
        )
        search_btn.pack(side='left', padx=(0, 20))
        
        # 筛选选项
        filter_row = ttk.Frame(filter_frame)
        filter_row.pack(fill='x')
        
        # 分类筛选
        ttk.Label(filter_row, text="Category:").pack(side='left', padx=(0, 5))
        self.products_category_var = tk.StringVar(value='all')
        category_combo = ttk.Combobox(
            filter_row,
            textvariable=self.products_category_var,
            values=['all', 'electronics', 'clothing', 'books', 'home', 'beauty'],
            state='readonly',
            width=15
        )
        category_combo.pack(side='left', padx=(0, 20))
        category_combo.bind('<<ComboboxSelected>>', self._on_products_filter_change)
        
        # 库存筛选
        ttk.Label(filter_row, text="Stock:").pack(side='left', padx=(0, 5))
        self.products_stock_var = tk.StringVar(value='all')
        stock_combo = ttk.Combobox(
            filter_row,
            textvariable=self.products_stock_var,
            values=['all', 'in_stock', 'low_stock', 'out_of_stock'],
            state='readonly',
            width=15
        )
        stock_combo.pack(side='left', padx=(0, 20))
        stock_combo.bind('<<ComboboxSelected>>', self._on_products_filter_change)
        
        # 添加商品按钮
        add_product_btn = ttk.Button(
            filter_row,
            text="➕ Add Product",
            command=self._create_add_product_dialog
        )
        add_product_btn.pack(side='right', padx=(0, 10))
        
        # 刷新按钮
        refresh_btn = ttk.Button(
            filter_row,
            text="Refresh",
            command=self._load_products_data
        )
        refresh_btn.pack(side='right')
    
    def _create_products_list(self, parent):
        """创建商品列表区域"""
        # 创建滚动框架
        list_frame = ttk.Frame(parent)
        list_frame.pack(fill='both', expand=True)
        
        # 创建Treeview
        columns = ('product_id', 'name', 'category', 'price', 'stock', 'sales', 'created_at', 'actions')
        self.products_tree = ttk.Treeview(list_frame, columns=columns, show='headings', height=15, style='Admin.Treeview')
        
        # 设置列标题
        self.products_tree.heading('product_id', text='Product ID')
        self.products_tree.heading('name', text='Product Name')
        self.products_tree.heading('category', text='Category')
        self.products_tree.heading('price', text='Price')
        self.products_tree.heading('stock', text='Stock')
        self.products_tree.heading('sales', text='Sales')
        self.products_tree.heading('created_at', text='Created At')
        self.products_tree.heading('actions', text='Actions')
        
        # 设置列宽
        self.products_tree.column('product_id', width=80)
        self.products_tree.column('name', width=200)
        self.products_tree.column('category', width=100)
        self.products_tree.column('price', width=80)
        self.products_tree.column('stock', width=80)
        self.products_tree.column('sales', width=80)
        self.products_tree.column('created_at', width=120)
        self.products_tree.column('actions', width=100)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient='vertical', command=self.products_tree.yview)
        self.products_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.products_tree.pack(side='left', fill='both', expand=True)
        scrollbar.pack(side='right', fill='y')
        
        # 绑定双击事件
        self.products_tree.bind('<Double-1>', self._on_product_double_click)
    
    def _on_products_search(self, event):
        """商品搜索事件处理"""
        # 应用搜索筛选并刷新显示
        filtered_products = self._filter_products(self.products_data)
        self._update_products_treeview(filtered_products)
    
    def _search_products(self):
        """搜索商品"""
        # 应用搜索筛选并刷新显示
        filtered_products = self._filter_products(self.products_data)
        self._update_products_treeview(filtered_products)
    
    def _on_products_filter_change(self, event):
        """商品筛选变化事件处理"""
        # 更新筛选条件
        self.product_filters['category'] = self.products_category_var.get()
        self.product_filters['stock'] = self.products_stock_var.get()
        
        # 应用筛选并刷新显示
        filtered_products = self._filter_products(self.products_data)
        self._update_products_treeview(filtered_products)
    
    def _filter_products(self, products):
        """筛选商品"""
        filtered = products
        
        # 分类筛选
        if self.product_filters['category'] != 'all':
            filtered = [p for p in filtered if p.get('category') == self.product_filters['category']]
        
        # 库存筛选
        if self.product_filters['stock'] != 'all':
            if self.product_filters['stock'] == 'in_stock':
                filtered = [p for p in filtered if p.get('stock', 0) > 10]
            elif self.product_filters['stock'] == 'low_stock':
                filtered = [p for p in filtered if 0 < p.get('stock', 0) <= 10]
            elif self.product_filters['stock'] == 'out_of_stock':
                filtered = [p for p in filtered if p.get('stock', 0) == 0]
        
        # 搜索筛选
        search_text = self.products_search_var.get().lower()
        if search_text:
            filtered = [p for p in filtered if 
                       search_text in p.get('name', '').lower() or
                       search_text in str(p.get('product_id', '')).lower()]
        
        return filtered
    
    def _update_products_treeview(self, products):
        """更新商品Treeview"""
        # 清空现有数据
        for item in self.products_tree.get_children():
            self.products_tree.delete(item)
        
        # 添加商品数据
        for product in products:
            category_display = self._get_category_display(product.get('category', ''))
            stock_display = self._get_stock_display(product.get('stock', 0))
            
            self.products_tree.insert('', 'end', values=(
                product.get('product_id', ''),
                product.get('name', ''),
                category_display,
                f"¥{product.get('price', 0):.2f}",
                stock_display,
                product.get('sales_count', 0),
                product.get('created_at', '')[:19] if product.get('created_at') else '',
                'View Details'
            ))
    
    def _get_category_display(self, category):
        """获取分类显示文本"""
        category_map = {
            'electronics': 'Electronics',
            'clothing': 'Clothing & Fashion',
            'books': 'Books & Education',
            'home': 'Home & Kitchen',
            'beauty': 'Beauty & Personal Care'
        }
        return category_map.get(category, category)
    
    def _get_stock_display(self, stock):
        """获取库存显示文本"""
        if stock > 10:
            return f"✅ {stock}"
        elif stock > 0:
            return f"⚠️ {stock}"
        else:
            return "❌ 0"
    
    def _on_product_double_click(self, event):
        """商品双击事件处理"""
        selection = self.products_tree.selection()
        if selection:
            item = self.products_tree.item(selection[0])
            product_id = item['values'][0]
            self._show_product_details(product_id)
    
    def _show_product_details(self, product_id):
        """显示商品详情"""
        try:
            # 查找商品
            product = None
            for p in self.products_data:
                if str(p.get('product_id')) == str(product_id):
                    product = p
                    break
            
            if not product:
                messagebox.showerror("错误", f"商品 {product_id} 不存在")
                return
            
            # 创建详情对话框
            self._create_product_details_dialog(product)
        except Exception as e:
            error(f"显示商品详情失败: {e}")
            messagebox.showerror("错误", f"显示商品详情时发生错误: {str(e)}")
    
    def _create_product_details_dialog(self, product):
        """创建商品详情对话框"""
        try:
            dialog = customtkinter.CTkToplevel(self)
            dialog.title(f"Product Details - {product.get('name', '')}")
            dialog.geometry("750x650")
            dialog.resizable(True, True)
            dialog.minsize(700, 550)
            
            # 设置对话框居中
            dialog.transient(self)
            dialog.grab_set()
            dialog.update_idletasks()
            x = (dialog.winfo_screenwidth() // 2) - (750 // 2)
            y = (dialog.winfo_screenheight() // 2) - (650 // 2)
            dialog.geometry(f"+{x}+{y}")
            
            # 主容器
            main_frame = customtkinter.CTkFrame(dialog, fg_color="transparent")
            main_frame.pack(fill='both', expand=True, padx=20, pady=20)
            
            # 标题
            title_label = customtkinter.CTkLabel(
                main_frame,
                text=f"🛍️ Product Details - {product.get('name', '')}",
                font=('Arial', 18, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            title_label.pack(pady=(0, 15))
            
            # 分隔线
            customtkinter.CTkFrame(main_frame, height=2, fg_color=Theme.get_color('border')).pack(fill='x', pady=(0, 20))
            
            # 商品基本信息
            info_frame = customtkinter.CTkFrame(main_frame, fg_color=("gray95", "gray20"))
            info_frame.pack(fill='x', pady=(0, 15), ipadx=15, ipady=15)
            
            info_title = customtkinter.CTkLabel(
                info_frame,
                text="📌 Product Information",
                font=('Arial', 14, 'bold'),
                text_color=Theme.get_color('fg_primary')
            )
            info_title.pack(anchor='w', pady=(0, 12))
            
            # 商品详细信息（使用更美观的格式）
            details = [
                ("Product ID:", product.get('product_id', '')),
                ("Product Name:", product.get('name', '')),
                ("Category:", self._get_category_display(product.get('category', ''))),
                ("Price:", f"¥{product.get('price', 0):.2f}"),
                ("Stock:", self._get_stock_display(product.get('stock', 0))),
                ("Sales Count:", str(product.get('sales_count', 0))),
                ("Created At:", product.get('created_at', '')),
                ("Updated At:", product.get('updated_at', 'None')),
                ("Description:", product.get('description', 'No description')[:80] + ('...' if len(product.get('description', '')) > 80 else ''))
            ]
            
            for label, value in details:
                detail_frame = customtkinter.CTkFrame(info_frame, fg_color="transparent")
                detail_frame.pack(fill='x', pady=4)
                customtkinter.CTkLabel(
                    detail_frame,
                    text=label,
                    font=('Arial', 11, 'bold'),
                    text_color=Theme.get_color('fg_secondary'),
                    width=130,
                    anchor='w'
                ).pack(side='left')
                customtkinter.CTkLabel(
                    detail_frame,
                    text=str(value),
                    font=('Arial', 11),
                    text_color=Theme.get_color('fg_primary'),
                    anchor='w'
                ).pack(side='left', fill='x', expand=True)
            
            # 操作按钮
            button_frame = customtkinter.CTkFrame(main_frame, fg_color="transparent")
            button_frame.pack(fill='x', pady=(15, 0))
            
            # 编辑商品按钮
            customtkinter.CTkButton(
                button_frame,
                text="Edit Product",
                command=lambda: self._edit_product_dialog(product, dialog),
                width=120,
                height=35,
                fg_color=Theme.get_color('accent'),
                hover_color=Theme.get_color('accent_hover'),
                corner_radius=8
            ).pack(side='left', padx=(0, 8))
            
            # 库存管理按钮
            customtkinter.CTkButton(
                button_frame,
                text="Manage Stock",
                command=lambda: self._manage_stock_dialog(product),
                width=120,
                height=35,
                fg_color=Theme.get_color('warning'),
                hover_color='#D68910',
                corner_radius=8
            ).pack(side='left', padx=(0, 8))
            
            # 删除商品按钮
            customtkinter.CTkButton(
                button_frame,
                text="Delete Product",
                command=lambda: self._delete_product_dialog(product),
                width=120,
                height=35,
                fg_color=Theme.get_color('error'),
                hover_color='#C0392B',
                corner_radius=8
            ).pack(side='left', padx=(0, 8))
            
            customtkinter.CTkButton(
                button_frame,
                text="Close",
                command=dialog.destroy,
                width=120,
                height=35,
                fg_color=Theme.get_color('fg_secondary'),
                hover_color=Theme.get_color('fg_tertiary'),
                corner_radius=8
            ).pack(side='right')
            
        except Exception as e:
            error(f"Failed to create product details dialog: {e}")
            messagebox.showerror("Error", f"Error occurred while creating product details dialog: {str(e)}")
    
    def _edit_product_dialog(self, product, parent_dialog=None):
        """创建商品编辑对话框"""
        try:
            edit_dialog = tk.Toplevel(self)
            edit_dialog.title(f"编辑商品 - {product.get('name', '')}")
            edit_dialog.geometry("600x750")
            edit_dialog.resizable(True, True)
            
            # 设置对话框居中
            edit_dialog.transient(self)
            edit_dialog.grab_set()
            
            # 表单框架
            form_frame = ttk.LabelFrame(edit_dialog, text="编辑商品信息", padding=15)
            form_frame.pack(fill='both', expand=True, padx=10, pady=10)
            
            # 商品名称
            ttk.Label(form_frame, text="商品名称:").grid(row=0, column=0, sticky='e', padx=5, pady=5)
            name_var = tk.StringVar(value=product.get('name', ''))
            name_entry = ttk.Entry(form_frame, textvariable=name_var, width=30)
            name_entry.grid(row=0, column=1, padx=5, pady=5)
            
            # 价格
            ttk.Label(form_frame, text="价格:").grid(row=1, column=0, sticky='e', padx=5, pady=5)
            price_var = tk.StringVar(value=str(product.get('price', 0)))
            price_entry = ttk.Entry(form_frame, textvariable=price_var, width=30)
            price_entry.grid(row=1, column=1, padx=5, pady=5)
            
            # 分类
            ttk.Label(form_frame, text="分类:").grid(row=2, column=0, sticky='e', padx=5, pady=5)
            category_var = tk.StringVar(value=product.get('category', 'electronics'))
            category_combo = ttk.Combobox(
                form_frame, 
                textvariable=category_var, 
                values=['electronics', 'clothing', 'books', 'home', 'beauty'], 
                state='readonly',
                width=27
            )
            category_combo.grid(row=2, column=1, padx=5, pady=5)
            
            # 描述
            ttk.Label(form_frame, text="描述:").grid(row=3, column=0, sticky='ne', padx=5, pady=5)
            description_var = tk.StringVar(value=product.get('description', ''))
            description_text = tk.Text(form_frame, height=4, width=30)
            description_text.grid(row=3, column=1, padx=5, pady=5)
            description_text.insert('1.0', product.get('description', ''))
            
            # 图片管理
            image_frame = ttk.LabelFrame(form_frame, text="商品图片", padding=10)
            image_frame.grid(row=4, column=0, columnspan=2, pady=10, sticky='ew')
            
            current_image_path = product.get('image_path')
            edit_image_path = None  # 用于存储新选择的图片路径
            
            # 创建持久化的图片信息显示label
            image_info_label = ttk.Label(image_frame, text="", foreground="blue")
            image_info_label.pack(pady=5)
            
            # 根据当前图片状态初始化显示
            if current_image_path and os.path.exists(current_image_path):
                image_info_label.config(
                    text=f"当前图片: {os.path.basename(current_image_path)}",
                    foreground="blue"
                )
            else:
                image_info_label.config(text="暂无图片", foreground="gray")
            
            def upload_new_image():
                from tkinter import filedialog
                nonlocal edit_image_path
                try:
                    file_path = filedialog.askopenfilename(
                        title="选择新图片",
                        filetypes=[("图片文件", "*.jpg *.jpeg *.png *.gif *.webp *.bmp"), ("所有文件", "*.*")]
                    )
                    
                    if file_path:
                        edit_image_path = file_path
                        filename = os.path.basename(file_path)
                        image_info_label.config(text=f"已选择新图片: {filename}", foreground="green")
                        info(f"选择新图片: {file_path}")
                except Exception as e:
                    error(f"选择图片失败: {e}")
                    messagebox.showerror("错误", f"选择图片失败: {str(e)}")
            
            btn_frame = ttk.Frame(image_frame)
            btn_frame.pack(pady=5)
            
            ttk.Button(btn_frame, text="📷 更换图片", command=upload_new_image).pack(side='left', padx=5)
            
            def remove_image():
                nonlocal edit_image_path
                edit_image_path = "REMOVE"
                image_info_label.config(text="已标记删除图片", foreground="orange")
                
                # 隐藏删除按钮，因为图片已被标记删除
                for widget in btn_frame.winfo_children():
                    if isinstance(widget, ttk.Button) and widget.cget('text') == "🗑️ 删除图片":
                        widget.pack_forget()
            
            if current_image_path:
                ttk.Button(btn_frame, text="🗑️ 删除图片", command=remove_image).pack(side='left', padx=5)
            
            # 按钮框架
            button_frame = ttk.Frame(edit_dialog)
            button_frame.pack(fill='x', padx=10, pady=10)
            
            def save_changes():
                try:
                    # 收集表单数据
                    new_name = name_var.get().strip()
                    new_price = price_var.get().strip()
                    new_category = category_var.get()
                    new_description = description_text.get('1.0', tk.END).strip()
                    
                    # 验证输入
                    if not new_name:
                        messagebox.showwarning("输入错误", "商品名称不能为空")
                        return
                    
                    try:
                        price_float = float(new_price)
                        if price_float < 0:
                            messagebox.showwarning("输入错误", "价格不能为负数")
                            return
                    except ValueError:
                        messagebox.showwarning("输入错误", "请输入有效的价格")
                        return
                    
                    # 处理图片
                    image_update_data = {}
                    if edit_image_path == "REMOVE":
                        # 标记删除图片
                        image_update_data['image_path'] = None
                        # 删除旧图片文件
                        if current_image_path and os.path.exists(current_image_path):
                            try:
                                from core.utils.image_utils import delete_product_image
                                delete_product_image(current_image_path)
                            except Exception as e:
                                error(f"删除旧图片失败: {e}")
                    elif edit_image_path:
                        # 上传新图片
                        try:
                            from core.utils.image_utils import copy_product_image
                            new_image_path = copy_product_image(
                                edit_image_path,
                                product.get('product_id'),
                                "data/product_images"
                            )
                            image_update_data['image_path'] = new_image_path
                            # 删除旧图片（如果存在）
                            if current_image_path and os.path.exists(current_image_path) and current_image_path != new_image_path:
                                try:
                                    from core.utils.image_utils import delete_product_image
                                    delete_product_image(current_image_path)
                                except Exception as e:
                                    error(f"删除旧图片失败: {e}")
                        except Exception as e:
                            error(f"上传新图片失败: {e}")
                            messagebox.showwarning("警告", f"图片上传失败: {str(e)}")
                    
                    # 确认更改
                    if messagebox.askyesno("确认更改", f"确定要更新商品信息吗？\n\n商品名称: {new_name}\n价格: ¥{price_float:.2f}\n分类: {self._get_category_display(new_category)}"):
                        # 调用服务更新商品信息
                        update_data = {
                            'name': new_name,
                            'price': price_float,
                            'category': new_category,
                            'description': new_description
                        }
                        update_data.update(image_update_data)
                        
                        success = self.admin_service.update_product_info(
                            product.get('product_id'), 
                            **update_data
                        )
                        
                        if success:
                            messagebox.showinfo("成功", "商品信息更新成功")
                            edit_dialog.destroy()
                            if parent_dialog:
                                parent_dialog.destroy()
                            # 刷新商品列表
                            self._load_products_data()
                        else:
                            messagebox.showerror("错误", "更新商品信息失败，请检查输入数据")
                
                except Exception as e:
                    error(f"保存商品信息失败: {e}")
                    messagebox.showerror("错误", f"保存商品信息时发生错误: {str(e)}")
            
            ttk.Button(button_frame, text="保存", command=save_changes).pack(side='left', padx=5)
            ttk.Button(button_frame, text="取消", command=edit_dialog.destroy).pack(side='right', padx=5)
            
        except Exception as e:
            error(f"创建商品编辑对话框失败: {e}")
            messagebox.showerror("错误", f"创建商品编辑对话框时发生错误: {str(e)}")
    
    def _manage_stock_dialog(self, product):
        """创建库存管理对话框"""
        try:
            stock_dialog = tk.Toplevel(self)
            stock_dialog.title(f"库存管理 - {product.get('name', '')}")
            stock_dialog.geometry("450x350")
            stock_dialog.resizable(True, True)
            
            # 设置对话框居中
            stock_dialog.transient(self)
            stock_dialog.grab_set()
            
            # 表单框架
            form_frame = ttk.LabelFrame(stock_dialog, text="库存管理", padding=15)
            form_frame.pack(fill='both', expand=True, padx=10, pady=10)
            
            # 当前库存显示
            current_stock = product.get('stock', 0)
            ttk.Label(form_frame, text=f"当前库存: {current_stock}", 
                     font=("Arial", 12, "bold")).grid(row=0, column=0, columnspan=2, pady=10)
            
            # 操作类型选择
            ttk.Label(form_frame, text="操作类型:").grid(row=1, column=0, sticky='e', padx=5, pady=5)
            operation_var = tk.StringVar(value='add')
            operation_combo = ttk.Combobox(
                form_frame, 
                textvariable=operation_var, 
                values=['add', 'subtract', 'set'], 
                state='readonly',
                width=20
            )
            operation_combo.grid(row=1, column=1, padx=5, pady=5)
            
            # 操作说明
            operation_labels = {
                'add': '补货：增加库存数量',
                'subtract': '减货：减少库存数量',
                'set': '设置：直接设置库存数量'
            }
            
            operation_label = ttk.Label(form_frame, text=operation_labels['add'], 
                                      font=("Arial", 9), foreground="#666")
            operation_label.grid(row=2, column=0, columnspan=2, pady=5)
            
            # 数量输入
            ttk.Label(form_frame, text="数量:").grid(row=3, column=0, sticky='e', padx=5, pady=5)
            amount_var = tk.StringVar()
            amount_entry = ttk.Entry(form_frame, textvariable=amount_var, width=22)
            amount_entry.grid(row=3, column=1, padx=5, pady=5)
            
            # 更新操作说明
            def update_operation_label(*args):
                operation = operation_var.get()
                operation_label.config(text=operation_labels[operation])
            
            operation_var.trace('w', update_operation_label)
            
            # 按钮框架
            button_frame = ttk.Frame(stock_dialog)
            button_frame.pack(fill='x', padx=10, pady=10)
            
            def adjust_stock():
                try:
                    amount_str = amount_var.get().strip()
                    operation = operation_var.get()
                    
                    # 验证输入
                    if not amount_str:
                        messagebox.showwarning("输入错误", "请输入数量")
                        return
                    
                    try:
                        amount = int(amount_str)
                        if amount < 0:
                            messagebox.showwarning("输入错误", "数量不能为负数")
                            return
                    except ValueError:
                        messagebox.showwarning("输入错误", "请输入有效的数量")
                        return
                    
                    # 计算新库存
                    if operation == 'add':
                        new_stock = current_stock + amount
                        action_text = f"补货 {amount} 件"
                    elif operation == 'subtract':
                        new_stock = max(0, current_stock - amount)
                        action_text = f"减货 {amount} 件"
                    else:  # set
                        new_stock = amount
                        action_text = f"设置库存为 {amount} 件"
                    
                    # 确认操作
                    if messagebox.askyesno("确认操作", f"确定要{action_text}吗？\n\n当前库存: {current_stock}\n操作后库存: {new_stock}"):
                        # 调用服务调整库存
                        success = self.admin_service.adjust_product_stock(
                            product.get('product_id'), 
                            amount, 
                            operation
                        )
                        
                        if success:
                            messagebox.showinfo("成功", f"库存调整成功！\n当前库存: {new_stock}")
                            stock_dialog.destroy()
                            # 刷新商品列表
                            self._load_products_data()
                        else:
                            messagebox.showerror("错误", "库存调整失败")
                
                except Exception as e:
                    error(f"调整库存失败: {e}")
                    messagebox.showerror("错误", f"调整库存时发生错误: {str(e)}")
            
            ttk.Button(button_frame, text="确认", command=adjust_stock).pack(side='left', padx=5)
            ttk.Button(button_frame, text="取消", command=stock_dialog.destroy).pack(side='right', padx=5)
            
        except Exception as e:
            error(f"创建库存管理对话框失败: {e}")
            messagebox.showerror("错误", f"创建库存管理对话框时发生错误: {str(e)}")
    
    def _delete_product_dialog(self, product):
        """创建删除商品对话框"""
        try:
            # 确认删除
            product_name = product.get('name', '')
            product_id = product.get('product_id', '')
            
            if messagebox.askyesno("确认删除", f"确定要删除商品吗？\n\n商品名称: {product_name}\n商品ID: {product_id}\n\n此操作不可撤销！"):
                # 再次确认
                if messagebox.askyesno("最终确认", "请再次确认删除操作：\n\n此操作将永久删除商品，无法恢复！\n\n确定要删除吗？"):
                    # 调用服务删除商品
                    success = self.admin_service.delete_product(product_id)
                    
                    if success:
                        messagebox.showinfo("成功", f"商品 {product_name} 删除成功")
                        # 刷新商品列表
                        self._load_products_data()
                    else:
                        messagebox.showerror("错误", "删除商品失败")
        
        except Exception as e:
            error(f"删除商品失败: {e}")
            messagebox.showerror("错误", f"删除商品时发生错误: {str(e)}")
    
    
    
    def _create_add_product_dialog(self):
        """创建添加商品对话框"""
        try:
            from tkinter import filedialog
            from core.utils.image_utils import copy_product_image
            
            add_dialog = tk.Toplevel(self)
            add_dialog.title("Add Product")
            add_dialog.geometry("650x750")
            add_dialog.resizable(True, True)
            add_dialog.minsize(600, 650)
            
            # 设置对话框居中
            add_dialog.transient(self)
            add_dialog.grab_set()
            
            # 居中显示
            add_dialog.update_idletasks()
            x = (add_dialog.winfo_screenwidth() // 2) - (650 // 2)
            y = (add_dialog.winfo_screenheight() // 2) - (750 // 2)
            add_dialog.geometry(f"+{x}+{y}")
            
            # 表单框架
            form_frame = ttk.LabelFrame(add_dialog, text="Product Information", padding=20)
            form_frame.pack(fill='both', expand=True, padx=15, pady=15)
            
            # 图片预览变量
            self.add_product_image_path = None
            self.add_product_preview_label = None
            
            # 商品名称
            ttk.Label(form_frame, text="商品名称:").grid(row=0, column=0, sticky='e', padx=5, pady=5)
            name_var = tk.StringVar()
            name_entry = ttk.Entry(form_frame, textvariable=name_var, width=30)
            name_entry.grid(row=0, column=1, padx=5, pady=5)
            
            # 价格
            ttk.Label(form_frame, text="价格:").grid(row=1, column=0, sticky='e', padx=5, pady=5)
            price_var = tk.StringVar()
            price_entry = ttk.Entry(form_frame, textvariable=price_var, width=30)
            price_entry.grid(row=1, column=1, padx=5, pady=5)
            
            # 分类
            ttk.Label(form_frame, text="分类:").grid(row=2, column=0, sticky='e', padx=5, pady=5)
            category_var = tk.StringVar(value='electronics')
            category_combo = ttk.Combobox(
                form_frame, 
                textvariable=category_var, 
                values=['electronics', 'clothing', 'books', 'home', 'beauty'], 
                state='readonly',
                width=27
            )
            category_combo.grid(row=2, column=1, padx=5, pady=5)
            
            # 库存
            ttk.Label(form_frame, text="库存:").grid(row=3, column=0, sticky='e', padx=5, pady=5)
            stock_var = tk.StringVar(value="0")
            stock_entry = ttk.Entry(form_frame, textvariable=stock_var, width=30)
            stock_entry.grid(row=3, column=1, padx=5, pady=5)
            
            # 描述
            ttk.Label(form_frame, text="描述:").grid(row=4, column=0, sticky='ne', padx=5, pady=5)
            description_text = tk.Text(form_frame, height=4, width=30)
            description_text.grid(row=4, column=1, padx=5, pady=5)
            
            # 图片上传
            image_frame = ttk.LabelFrame(form_frame, text="Product Image", padding=12)
            image_frame.grid(row=5, column=0, columnspan=2, pady=15, sticky='ew')
            
            # 图片预览标签
            self.add_product_preview_label = ttk.Label(image_frame, text="暂无图片", width=30)
            self.add_product_preview_label.pack(pady=5)
            
            def upload_image():
                try:
                    from core.utils.image_utils import validate_image_file
                    
                    file_path = filedialog.askopenfilename(
                        title="选择商品图片",
                        filetypes=[("图片文件", "*.jpg *.jpeg *.png *.gif *.webp *.bmp"), ("所有文件", "*.*")]
                    )
                    
                    if file_path:
                        # 验证图片
                        is_valid, error_msg = validate_image_file(file_path, max_size_mb=10)
                        if not is_valid:
                            messagebox.showwarning("图片验证失败", error_msg)
                            return
                        
                        self.add_product_image_path = file_path
                        # 显示文件名
                        filename = os.path.basename(file_path)
                        self.add_product_preview_label.config(text=f"已选择: {filename}")
                        info(f"选择图片: {file_path}")
                except Exception as e:
                    error(f"选择图片失败: {e}")
                    messagebox.showerror("错误", f"选择图片失败: {str(e)}")
            
            upload_btn = ttk.Button(image_frame, text="📷 选择图片", command=upload_image)
            upload_btn.pack(pady=5)
            
            # 按钮框架
            button_frame = ttk.Frame(add_dialog)
            button_frame.pack(fill='x', padx=15, pady=(10, 15))
            
            def save_product():
                try:
                    # 收集表单数据
                    name = name_var.get().strip()
                    price = price_var.get().strip()
                    category = category_var.get()
                    stock = stock_var.get().strip()
                    description = description_text.get('1.0', tk.END).strip()
                    
                    # 验证输入
                    if not name:
                        messagebox.showwarning("Input Error", "Product name cannot be empty")
                        return
                    
                    try:
                        price_float = float(price)
                        if price_float < 0:
                            messagebox.showwarning("Input Error", "Price cannot be negative")
                            return
                    except ValueError:
                        messagebox.showwarning("Input Error", "Please enter a valid price")
                        return
                    
                    try:
                        stock_int = int(stock)
                        if stock_int < 0:
                            messagebox.showwarning("Input Error", "Stock cannot be negative")
                            return
                    except ValueError:
                        messagebox.showwarning("Input Error", "Please enter a valid stock quantity")
                        return
                    
                    # 验证图片
                    image_path = None
                    if self.add_product_image_path:
                        try:
                            from core.utils.image_utils import validate_image_file
                            # 再次验证图片
                            is_valid, error_msg = validate_image_file(self.add_product_image_path, max_size_mb=10)
                            if not is_valid:
                                messagebox.showwarning("Image Validation Failed", f"Image validation failed: {error_msg}")
                                return
                            image_path = self.add_product_image_path
                        except Exception as e:
                            error(f"Image validation failed: {e}")
                            messagebox.showerror("Error", f"Error occurred while validating image: {str(e)}")
                            return
                    
                    # 构建商品数据
                    product_data = {
                        'name': name,
                        'price': price_float,
                        'category': category,
                        'stock': stock_int,
                        'description': description,
                        'seller_id': 'admin_001'  # 默认卖家ID
                    }
                    
                    # 先添加商品以获取 product_id
                    new_product_obj = self.admin_service.add_new_product(product_data)
                    
                    if new_product_obj:
                        # 使用返回的商品对象获取ID
                        new_product_id = new_product_obj.product_id
                        
                        if image_path:
                            # 复制图片到 product_images 目录
                            try:
                                # 验证图片格式和大小
                                from core.utils.image_utils import validate_image_file
                                is_valid, error_msg = validate_image_file(image_path, max_size_mb=10)
                                if not is_valid:
                                    warning(f"Image validation failed: {error_msg}")
                                    messagebox.showwarning("Warning", f"Product added successfully, but image validation failed: {error_msg}")
                                else:
                                    target_image_path = copy_product_image(
                                        image_path, 
                                        new_product_id,
                                        "data/product_images"
                                    )
                                    # 更新商品的图片路径
                                    self.admin_service.update_product_info(
                                        new_product_id,
                                        image_path=target_image_path
                                    )
                                    info(f"Product image uploaded: {target_image_path}")
                            except ValueError as ve:
                                error(f"Image validation failed: {ve}")
                                messagebox.showwarning("Warning", f"Product added successfully, but image validation failed: {str(ve)}")
                            except Exception as e:
                                error(f"Failed to upload image: {e}")
                                messagebox.showwarning("Warning", f"Product added successfully, but image upload failed: {str(e)}")
                        
                        messagebox.showinfo("Success", "Product added successfully!")
                        add_dialog.destroy()
                        # 切换到商品标签页并刷新商品列表
                        if self.current_tab != "products":
                            self._switch_tab("products")
                        else:
                            self._load_products_data()
                    else:
                        messagebox.showerror("Error", "Failed to add product")
                
                except Exception as e:
                    error(f"Failed to save product: {e}")
                    messagebox.showerror("Error", f"Error occurred while saving product: {str(e)}")
            
            ttk.Button(button_frame, text="Save", command=save_product, style='Accent.TButton', width=15).pack(side='right', padx=(8, 0))
            ttk.Button(button_frame, text="Cancel", command=add_dialog.destroy, width=15).pack(side='right')
            
        except Exception as e:
            error(f"Failed to create add product dialog: {e}")
            messagebox.showerror("Error", f"Error occurred while creating add product dialog: {str(e)}")
    
    def _logout(self):
        """退出登录"""
        if messagebox.askyesno("确认", "确定要退出管理员登录吗？"):
            self.controller.auth_service.logout()
            self.controller.show_page("WelcomePage")
    
    def update_data(self):
        """更新页面数据"""
        if self.current_tab == "orders":
            self._load_orders_data()
    
    def refresh_language(self):
        """刷新语言显示"""
        # 这里可以添加语言刷新逻辑
        pass
    
    def on_show(self):
        """页面显示时调用"""
        if hasattr(self, 'role_switcher'):
            self.role_switcher.update_display()
